home *** CD-ROM | disk | FTP | other *** search
/ Info-Mac 4 / Info_Mac IV CD-ROM (Pacific HiTech Inc.)(August 1994).iso / Applications / gdbm-1.7.3 / source / alloca.c next >
Text File  |  1994-05-21  |  13KB  |  464 lines

  1. /* alloca.c -- allocate automatically reclaimed memory
  2.    (Mostly) portable public-domain implementation -- D A Gwyn
  3.  
  4.    This implementation of the PWB library alloca function,
  5.    which is used to allocate space off the run-time stack so
  6.    that it is automatically reclaimed upon procedure exit,
  7.    was inspired by discussions with J. Q. Johnson of Cornell.
  8.    J.Otto Tennant <jot@cray.com> contributed the Cray support.
  9.  
  10.    There are some preprocessor constants that can
  11.    be defined when compiling for your specific system, for
  12.    improved efficiency; however, the defaults should be okay.
  13.  
  14.    The general concept of this implementation is to keep
  15.    track of all alloca-allocated blocks, and reclaim any
  16.    that are found to be deeper in the stack than the current
  17.    invocation.  This heuristic does not reclaim storage as
  18.    soon as it becomes invalid, but it will do so eventually.
  19.  
  20.    As a special case, alloca(0) reclaims storage without
  21.    allocating any.  It is a good idea to use alloca(0) in
  22.    your main control loop, etc. to force garbage collection.  */
  23.  
  24. /* include system configuration before all else. */
  25. #include "autoconf.h"
  26.  
  27. #if HAVE_STDLIB_H
  28. #include <stdlib.h>
  29. #endif
  30.  
  31. /* If compiling with GCC, this file's not needed.  */
  32. #ifndef alloca
  33.  
  34. #ifdef emacs
  35. #ifdef static
  36. /* actually, only want this if static is defined as ""
  37.    -- this is for usg, in which emacs must undefine static
  38.    in order to make unexec workable
  39.    */
  40. #ifndef STACK_DIRECTION
  41. you
  42. lose
  43. -- must know STACK_DIRECTION at compile-time
  44. #endif /* STACK_DIRECTION undefined */
  45. #endif /* static */
  46. #endif /* emacs */
  47.  
  48. /* If your stack is a linked list of frames, you have to
  49.    provide an "address metric" ADDRESS_FUNCTION macro.  */
  50.  
  51. #ifdef CRAY
  52. long i00afunc ();
  53. #define ADDRESS_FUNCTION(arg) (char *) i00afunc (&(arg))
  54. #else
  55. #define ADDRESS_FUNCTION(arg) &(arg)
  56. #endif
  57.  
  58. #if __STDC__
  59. typedef void *pointer;
  60. #else
  61. typedef char *pointer;
  62. #endif
  63.  
  64. #define    NULL    0
  65.  
  66. /* Define STACK_DIRECTION if you know the direction of stack
  67.    growth for your system; otherwise it will be automatically
  68.    deduced at run-time.
  69.  
  70.    STACK_DIRECTION > 0 => grows toward higher addresses
  71.    STACK_DIRECTION < 0 => grows toward lower addresses
  72.    STACK_DIRECTION = 0 => direction of growth unknown  */
  73.  
  74. #ifndef STACK_DIRECTION
  75. #define    STACK_DIRECTION    0    /* Direction unknown.  */
  76. #endif
  77.  
  78. #if STACK_DIRECTION != 0
  79.  
  80. #define    STACK_DIR    STACK_DIRECTION    /* Known at compile-time.  */
  81.  
  82. #else /* STACK_DIRECTION == 0; need run-time code.  */
  83.  
  84. static int stack_dir;        /* 1 or -1 once known.  */
  85. #define    STACK_DIR    stack_dir
  86.  
  87. static void
  88. find_stack_direction ()
  89. {
  90.   static char *addr = NULL;    /* Address of first `dummy', once known.  */
  91.   auto char dummy;        /* To get stack address.  */
  92.  
  93.   if (addr == NULL)
  94.     {                /* Initial entry.  */
  95.       addr = ADDRESS_FUNCTION (dummy);
  96.  
  97.       find_stack_direction ();    /* Recurse once.  */
  98.     }
  99.   else
  100.     {
  101.       /* Second entry.  */
  102.       if (ADDRESS_FUNCTION (dummy) > addr)
  103.     stack_dir = 1;        /* Stack grew upward.  */
  104.       else
  105.     stack_dir = -1;        /* Stack grew downward.  */
  106.     }
  107. }
  108.  
  109. #endif /* STACK_DIRECTION == 0 */
  110.  
  111. /* An "alloca header" is used to:
  112.    (a) chain together all alloca'ed blocks;
  113.    (b) keep track of stack depth.
  114.  
  115.    It is very important that sizeof(header) agree with malloc
  116.    alignment chunk size.  The following default should work okay.  */
  117.  
  118. #ifndef    ALIGN_SIZE
  119. #define    ALIGN_SIZE    sizeof(double)
  120. #endif
  121.  
  122. typedef union hdr
  123. {
  124.   char align[ALIGN_SIZE];    /* To force sizeof(header).  */
  125.   struct
  126.     {
  127.       union hdr *next;        /* For chaining headers.  */
  128.       char *deep;        /* For stack depth measure.  */
  129.     } h;
  130. } header;
  131.  
  132. static header *last_alloca_header = NULL;    /* -> last alloca header.  */
  133.  
  134. /* Return a pointer to at least SIZE bytes of storage,
  135.    which will be automatically reclaimed upon exit from
  136.    the procedure that called alloca.  Originally, this space
  137.    was supposed to be taken from the current stack frame of the
  138.    caller, but that method cannot be made to work for some
  139.    implementations of C, for example under Gould's UTX/32.  */
  140.  
  141. pointer
  142. alloca (size)
  143.      unsigned size;
  144. {
  145.   auto char probe;        /* Probes stack depth: */
  146.   register char *depth = ADDRESS_FUNCTION (probe);
  147.  
  148. #if STACK_DIRECTION == 0
  149.   if (STACK_DIR == 0)        /* Unknown growth direction.  */
  150.     find_stack_direction ();
  151. #endif
  152.  
  153.   /* Reclaim garbage, defined as all alloca'd storage that
  154.      was allocated from deeper in the stack than currently. */
  155.  
  156.   {
  157.     register header *hp;    /* Traverses linked list.  */
  158.  
  159.     for (hp = last_alloca_header; hp != NULL;)
  160.       if ((STACK_DIR > 0 && hp->h.deep > depth)
  161.       || (STACK_DIR < 0 && hp->h.deep < depth))
  162.     {
  163.       register header *np = hp->h.next;
  164.  
  165.       free ((pointer) hp);    /* Collect garbage.  */
  166.  
  167.       hp = np;        /* -> next header.  */
  168.     }
  169.       else
  170.     break;            /* Rest are not deeper.  */
  171.  
  172.     last_alloca_header = hp;    /* -> last valid storage.  */
  173.   }
  174.  
  175.   if (size == 0)
  176.     return NULL;        /* No allocation required.  */
  177.  
  178.   /* Allocate combined header + user data storage.  */
  179.  
  180.   {
  181.     register pointer new = malloc (sizeof (header) + size);
  182.     /* Address of header.  */
  183.  
  184.     ((header *) new)->h.next = last_alloca_header;
  185.     ((header *) new)->h.deep = depth;
  186.  
  187.     last_alloca_header = (header *) new;
  188.  
  189.     /* User storage begins just after header.  */
  190.  
  191.     return (pointer) ((char *) new + sizeof (header));
  192.   }
  193. }
  194.  
  195. #ifdef CRAY
  196.  
  197. #ifdef DEBUG_I00AFUNC
  198. #include <stdio.h>
  199. #endif
  200.  
  201. #ifndef CRAY_STACK
  202. #define CRAY_STACK
  203. #ifndef CRAY2
  204. /* Stack structures for CRAY-1, CRAY X-MP, and CRAY Y-MP */
  205. struct stack_control_header
  206.   {
  207.     long shgrow:32;        /* Number of times stack has grown.  */
  208.     long shaseg:32;        /* Size of increments to stack.  */
  209.     long shhwm:32;        /* High water mark of stack.  */
  210.     long shsize:32;        /* Current size of stack (all segments).  */
  211.   };
  212.  
  213. /* The stack segment linkage control information occurs at
  214.    the high-address end of a stack segment.  (The stack
  215.    grows from low addresses to high addresses.)  The initial
  216.    part of the stack segment linkage control information is
  217.    0200 (octal) words.  This provides for register storage
  218.    for the routine which overflows the stack.  */
  219.  
  220. struct stack_segment_linkage
  221.   {
  222.     long ss[0200];        /* 0200 overflow words.  */
  223.     long sssize:32;        /* Number of words in this segment.  */
  224.     long ssbase:32;        /* Offset to stack base.  */
  225.     long:32;
  226.     long sspseg:32;        /* Offset to linkage control of previous
  227.                    segment of stack.  */
  228.     long:32;
  229.     long sstcpt:32;        /* Pointer to task common address block.  */
  230.     long sscsnm;        /* Private control structure number for
  231.                    microtasking.  */
  232.     long ssusr1;        /* Reserved for user.  */
  233.     long ssusr2;        /* Reserved for user.  */
  234.     long sstpid;        /* Process ID for pid based multi-tasking.  */
  235.     long ssgvup;        /* Pointer to multitasking thread giveup.  */
  236.     long sscray[7];        /* Reserved for Cray Research.  */
  237.     long ssa0;
  238.     long ssa1;
  239.     long ssa2;
  240.     long ssa3;
  241.     long ssa4;
  242.     long ssa5;
  243.     long ssa6;
  244.     long ssa7;
  245.     long sss0;
  246.     long sss1;
  247.     long sss2;
  248.     long sss3;
  249.     long sss4;
  250.     long sss5;
  251.     long sss6;
  252.     long sss7;
  253.   };
  254.  
  255. #else /* CRAY2 */
  256. /* The following structure defines the vector of words
  257.    returned by the STKSTAT library routine.  */
  258. struct stk_stat
  259.   {
  260.     long now;            /* Current total stack size.  */
  261.     long maxc;            /* Amount of contiguous space which would
  262.                    be required to satisfy the maximum
  263.                    stack demand to date.  */
  264.     long high_water;        /* Stack high-water mark.  */
  265.     long overflows;        /* Number of stack overflow ($STKOFEN) calls.  */
  266.     long hits;            /* Number of internal buffer hits.  */
  267.     long extends;        /* Number of block extensions.  */
  268.     long stko_mallocs;        /* Block allocations by $STKOFEN.  */
  269.     long underflows;        /* Number of stack underflow calls ($STKRETN).  */
  270.     long stko_free;        /* Number of deallocations by $STKRETN.  */
  271.     long stkm_free;        /* Number of deallocations by $STKMRET.  */
  272.     long segments;        /* Current number of stack segments.  */
  273.     long maxs;            /* Maximum number of stack segments so far.  */
  274.     long pad_size;        /* Stack pad size.  */
  275.     long current_address;    /* Current stack segment address.  */
  276.     long current_size;        /* Current stack segment size.  This
  277.                    number is actually corrupted by STKSTAT to
  278.                    include the fifteen word trailer area.  */
  279.     long initial_address;    /* Address of initial segment.  */
  280.     long initial_size;        /* Size of initial segment.  */
  281.   };
  282.  
  283. /* The following structure describes the data structure which trails
  284.    any stack segment.  I think that the description in 'asdef' is
  285.    out of date.  I only describe the parts that I am sure about.  */
  286.  
  287. struct stk_trailer
  288.   {
  289.     long this_address;        /* Address of this block.  */
  290.     long this_size;        /* Size of this block (does not include
  291.                    this trailer).  */
  292.     long unknown2;
  293.     long unknown3;
  294.     long link;            /* Address of trailer block of previous
  295.                    segment.  */
  296.     long unknown5;
  297.     long unknown6;
  298.     long unknown7;
  299.     long unknown8;
  300.     long unknown9;
  301.     long unknown10;
  302.     long unknown11;
  303.     long unknown12;
  304.     long unknown13;
  305.     long unknown14;
  306.   };
  307.  
  308. #endif /* CRAY2 */
  309. #endif /* not CRAY_STACK */
  310.  
  311. #ifdef CRAY2
  312. /* Determine a "stack measure" for an arbitrary ADDRESS.
  313.    I doubt that "lint" will like this much. */
  314.  
  315. static long
  316. i00afunc (long *address)
  317. {
  318.   struct stk_stat status;
  319.   struct stk_trailer *trailer;
  320.   long *block, size;
  321.   long result = 0;
  322.  
  323.   /* We want to iterate through all of the segments.  The first
  324.      step is to get the stack status structure.  We could do this
  325.      more quickly and more directly, perhaps, by referencing the
  326.      $LM00 common block, but I know that this works.  */
  327.  
  328.   STKSTAT (&status);
  329.  
  330.   /* Set up the iteration.  */
  331.  
  332.   trailer = (struct stk_trailer *) (status.current_address
  333.                     + status.current_size
  334.                     - 15);
  335.  
  336.   /* There must be at least one stack segment.  Therefore it is
  337.      a fatal error if "trailer" is null.  */
  338.  
  339.   if (trailer == 0)
  340.     abort ();
  341.  
  342.   /* Discard segments that do not contain our argument address.  */
  343.  
  344.   while (trailer != 0)
  345.     {
  346.       block = (long *) trailer->this_address;
  347.       size = trailer->this_size;
  348.       if (block == 0 || size == 0)
  349.     abort ();
  350.       trailer = (struct stk_trailer *) trailer->link;
  351.       if ((block <= address) && (address < (block + size)))
  352.     break;
  353.     }
  354.  
  355.   /* Set the result to the offset in this segment and add the sizes
  356.      of all predecessor segments.  */
  357.  
  358.   result = address - block;
  359.  
  360.   if (trailer == 0)
  361.     {
  362.       return result;
  363.     }
  364.  
  365.   do
  366.     {
  367.       if (trailer->this_size <= 0)
  368.     abort ();
  369.       result += trailer->this_size;
  370.       trailer = (struct stk_trailer *) trailer->link;
  371.     }
  372.   while (trailer != 0);
  373.  
  374.   /* We are done.  Note that if you present a bogus address (one
  375.      not in any segment), you will get a different number back, formed
  376.      from subtracting the address of the first block.  This is probably
  377.      not what you want.  */
  378.  
  379.   return (result);
  380. }
  381.  
  382. #else /* not CRAY2 */
  383. /* Stack address function for a CRAY-1, CRAY X-MP, or CRAY Y-MP.
  384.    Determine the number of the cell within the stack,
  385.    given the address of the cell.  The purpose of this
  386.    routine is to linearize, in some sense, stack addresses
  387.    for alloca.  */
  388.  
  389. static long
  390. i00afunc (long address)
  391. {
  392.   long stkl = 0;
  393.  
  394.   long size, pseg, this_segment, stack;
  395.   long result = 0;
  396.  
  397.   struct stack_segment_linkage *ssptr;
  398.  
  399.   /* Register B67 contains the address of the end of the
  400.      current stack segment.  If you (as a subprogram) store
  401.      your registers on the stack and find that you are past
  402.      the contents of B67, you have overflowed the segment.
  403.  
  404.      B67 also points to the stack segment linkage control
  405.      area, which is what we are really interested in.  */
  406.  
  407.   stkl = CRAY_STACKSEG_END ();
  408.   ssptr = (struct stack_segment_linkage *) stkl;
  409.  
  410.   /* If one subtracts 'size' from the end of the segment,
  411.      one has the address of the first word of the segment.
  412.  
  413.      If this is not the first segment, 'pseg' will be
  414.      nonzero.  */
  415.  
  416.   pseg = ssptr->sspseg;
  417.   size = ssptr->sssize;
  418.  
  419.   this_segment = stkl - size;
  420.  
  421.   /* It is possible that calling this routine itself caused
  422.      a stack overflow.  Discard stack segments which do not
  423.      contain the target address.  */
  424.  
  425.   while (!(this_segment <= address && address <= stkl))
  426.     {
  427. #ifdef DEBUG_I00AFUNC
  428.       fprintf (stderr, "%011o %011o %011o\n", this_segment, address, stkl);
  429. #endif
  430.       if (pseg == 0)
  431.     break;
  432.       stkl = stkl - pseg;
  433.       ssptr = (struct stack_segment_linkage *) stkl;
  434.       size = ssptr->sssize;
  435.       pseg = ssptr->sspseg;
  436.       this_segment = stkl - size;
  437.     }
  438.  
  439.   result = address - this_segment;
  440.  
  441.   /* If you subtract pseg from the current end of the stack,
  442.      you get the address of the previous stack segment's end.
  443.      This seems a little convoluted to me, but I'll bet you save
  444.      a cycle somewhere.  */
  445.  
  446.   while (pseg != 0)
  447.     {
  448. #ifdef DEBUG_I00AFUNC
  449.       fprintf (stderr, "%011o %011o\n", pseg, size);
  450. #endif
  451.       stkl = stkl - pseg;
  452.       ssptr = (struct stack_segment_linkage *) stkl;
  453.       size = ssptr->sssize;
  454.       pseg = ssptr->sspseg;
  455.       result += size;
  456.     }
  457.   return (result);
  458. }
  459.  
  460. #endif /* not CRAY2 */
  461. #endif /* CRAY */
  462.  
  463. #endif /* no alloca */
  464.